<style>
</style>

<script>
import PatrolGroupForm, { WeekdaysMap } from './patrolGroupForm.vue'
import DialogContent from "@/components/DialogContent/index.vue"
import { patrolPlans, availableMembers, particularDates, createPatrolGroup } from '@/api/watchman'
export default {
  components: {
    PatrolGroupForm,
    DialogContent
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default() {
        return false
      }
    },
    title: {
      type: String,
      required: false,
      default: '添加巡防小组'
    },
    confirmText: {
      type: String,
      required: false,
      default: '保存'
    },
    cancelText: {
      type: String,
      required: false,
      default: '取消'
    }
  },
  data() {
    return {
      form: {
        groupName: '',
        membersSelected: [],
        particularDatesSelected: [],
        isIgnoreLegalHolidays: false,
        rules: []
      },
      members: [],
      plans: [],
      particularDates: [],

      loadingStatuses: {
        loading: false,
        submit: false
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isShow() {
      return this.dialogVisible
    },
    isActionDisabled() {
      const { loading, submit } = this.loadingStatuses
      return loading || submit
    }
  },
  watch: {
    isShow(isShow) {
      if (isShow) {
        console.log(isShow)
        this.initData()
      }
    }
  },
  methods: {
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    closeDialog() {
      this.dialogVisible = false
    },
    async fetchMembers(kw) {
      const params = { name: kw,paginate:10000 }
      await availableMembers(params)
        .then(result => this.members = result.data)
    },
    async fetchPatrolPlans(kw) {
      const params = { name: kw,paginate:10000 }
      await patrolPlans(params)
        .then(result => this.plans = result.data)
    },
    async fetchParticularDates() {
      let params = {
        sort:'asc'
      }
      await particularDates(params)
        .then(result => this.particularDates = result.data)
    },
    async loadData() {
      Promise.allSettled([
        this.fetchMembers(),
        this.fetchPatrolPlans(),
        this.fetchParticularDates()
      ])
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (error) {
        this.loadingStatuses.loading = false
        console.log(error)
      }
    },
    buildParams() {
      const {
        groupName,
        membersSelected,
        particularDatesSelected,
        isIgnoreLegalHolidays,
        rules
      } = this.form

      const rulesFormatted = rules.map(rule => {
        const { patrolPlan, days } = rule
        return {
          weeks: days.map(day => day.value),
          class_id: patrolPlan.id
        }
      })

      const params = {
        name: groupName,
        userId: JSON.stringify(membersSelected),
        legal_holidays: isIgnoreLegalHolidays ? 1 : 0,
        times: JSON.stringify(rulesFormatted),
        date: JSON.stringify(particularDatesSelected)
      }

      return params
    },
    async submit() {
      try {
        const flag = await this.$refs?.form.validate()
        if (!flag) return

        this.loadingStatuses.submit = true

        const params = this.buildParams()
        await this.sleep(300)
        const result = await createPatrolGroup(params)

                this.$refs?.form.resetForm()
                this.loadingStatuses.submit = false
                this.$emit('success', result)
      } catch (error) {
        this.$emit('fail', error)

        this.loadingStatuses.submit = false
        console.log(error)
      }
    }

  }
}
</script>

<template>
  <DialogContent :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
    width="45%"
    destroy-on-close>
    <div v-loading="loadingStatuses.loading" class="body">
      <PatrolGroupForm
        ref="form"
        v-model="form"
        :col-size="24"
        :fetch-members-fn="fetchMembers"
        :fetch-patrol-plans-fn="fetchPatrolPlans"
        :fetch-particular-dates-fn="fetchParticularDates"
        :members="members"
        :plans="plans"
        :particular-dates="particularDates"
        :disabled="false"
        :init="false"
      />
    </div>

    <div slot="footer">
      <el-button
        type="primary"
        :disabled="isActionDisabled"
        :loading="loadingStatuses.submit"
        @click="submit"
      >
        {{ confirmText }}
      </el-button>

      <el-button
        :disabled="loadingStatuses.submit"
        @click="closeDialog"
      >
        {{ cancelText }}
      </el-button>
    </div>
  </DialogContent>
</template>
